package cqrtplm.aop;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.basic.dto.defaultvalue.TyplmAttrDefaultValueDTO;
import com.hustcad.plm.basic.dto.defaultvalue.TyplmDefaultValueParamDTO;
import com.hustcad.plm.basic.log.LogEventEnum;
import com.hustcad.plm.basic.util.TyplmEntityBaseUtil;
import com.hustcad.plm.pdm.audit.util.TyplmAuditLogUtil;
import com.hustcad.plm.pdm.classification.model.dto.TyplmClassificationEntityDTO;
import com.hustcad.plm.pdm.classification.service.TyplmClassificationService;
import com.hustcad.plm.pdm.comment.model.dto.QueryCommentCountDTO;
import com.hustcad.plm.pdm.comment.model.vo.CommentCountVO;
import com.hustcad.plm.pdm.defaultvalue.TyplmDefaultValueService;
import com.hustcad.plm.pdm.file.model.dto.UploadFileDTO;
import com.hustcad.plm.pdm.folder.model.dto.HyperlinkDTO;
import com.hustcad.plm.pdm.folder.model.vo.SubfolderVO;
import com.hustcad.plm.pdm.folder.model.vo.SubfolderWebVO;
import com.hustcad.plm.pdm.folder.service.TyplmHyperlinkService;
import com.hustcad.plm.pdm.folder.service.TyplmSubFolderLinkService;
import com.hustcad.plm.pdm.form.model.vo.PdmForm;
import com.hustcad.plm.pdm.form.model.vo.PdmFormColumn;
import com.hustcad.plm.pdm.middle.partbom.service.TyplmPdmPartService;
import com.hustcad.plm.pdm.partbom.dto.InsertPartDTO;
import com.hustcad.plm.pdm.partbom.enums.PartBomErrorCodeEnum;
import com.hustcad.plm.pdm.partbom.vo.PdmPartInfoVO;
import com.hustcad.plm.pdm.type.service.TyplmTypeService;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.audit.AuditLogDO;
import com.ty.basic.response.ResponseResult;
import com.ty.basic.utils.ArgumentUtils;
import com.ty.basic.vo.TyAttributeDefMapVO;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.entity.ObjectStorageDO;
import cqrtplm.mapper.RTClassificationMapper;
import cqrtplm.mapper.StoragePlanningMapper;
import cqrtplm.service.DocFolderOperationService;
import cqrtplm.service.ObjectStorageService;
import cqrtplm.vo.PDFProjectVO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.LinkedMap;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Aspect
@Component
@Slf4j
@Order(Ordered.LOWEST_PRECEDENCE)
public class PartCreateAOP {

    @Resource
    private TyplmPdmPartService typlmPdmPartService;

    @Resource
    private StoragePlanningMapper storagePlanningMapper;

    @Resource
    private TyplmSubFolderLinkService typlmSubFolderLinkService;

    @Resource
    private DocFolderOperationService docFolderOperationService;

    @Resource
    private TyplmHyperlinkService typlmHyperlinkService;

    @Resource
    private ObjectStorageService objectStorageService;

    @Value("${ipd.base.url:http://127.0.0.1:9588}")
    private String ipdUrl;

    //    /**
    //     * 创建时去重
    //     * @param proceedingJoinPoint
    //     * @return
    //     * @throws Throwable
    //     */
    //    @Around("execution(* com.hustcad.plm.pdm.middle.partbom.service.impl.TyplmPdmPartServiceImpl.insertPart(com.hustcad.plm.pdm.file.model.dto.UploadFileDTO, java.util.Map<java.lang.String,java.lang.String>, com.hustcad.plm.pdm.partbom.dto.InsertPartDTO))")
    //    public Object insertPart(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    //        Object[] args = proceedingJoinPoint.getArgs();
    //        log.info("??????>>>>>>>>>>{}", args);
    //        InsertPartDTO insertPart = (InsertPartDTO) args[2];
    //        LinkedHashMap<String, List<String>> ibaAttribute = insertPart.getIbaAttribute();
    //        List<String> strings = ibaAttribute.get("CompleteDescription");
    //        JSONArray jsonArray = new JSONArray();
    //        Map<String, Object> map = new HashMap<>();
    //        map.put("CompleteDescription", strings.get(0));
    //        jsonArray.add(map);
    //        queryObjectByIbaValueAndType(new BigInteger(insertPart.getTypeOid()), insertPart.getTypeOType(),jsonArray);
    //        return proceedingJoinPoint.proceed();
    //    }
    //
    //    public void queryObjectByIbaValueAndType(BigInteger typeOid, String typeName, JSONArray ibaList) {
    //        SearchConditionDTO searchConditionDTO = new SearchConditionDTO();
    //        List<SearchTypeDTO> typeList = new ArrayList<>();
    //        SearchTypeDTO searchTypeDTO = new SearchTypeDTO();
    //        searchTypeDTO.setTypeOid(typeOid);
    //        searchTypeDTO.setTypeInthid(typeName);
    //        typeList.add(searchTypeDTO);
    //        searchConditionDTO.setTypeList(typeList);
    //        searchConditionDTO.setContextList(new ArrayList<>());
    //        searchConditionDTO.setConditionJoint("and");
    //        List<SearchTypeVO> list = new ArrayList<>();
    //        SearchTypeVO searchTypeVO = new SearchTypeVO();
    //        searchTypeVO.setTypeOid(typeOid);
    //        searchTypeVO.setTypeInthid(typeName);
    //        list.add(searchTypeVO);
    //        List<SearchAttributeVO> searchAttribute = typlmCommonSearchService.getSearchAttribute(list);
    //        List<SearchColumnDTO> searchAttributeDTOS = new ArrayList<>();
    //        try {
    //            BeanUtils.copyProperties(searchAttributeDTOS, searchAttribute);
    //        } catch (Exception e) {
    //            throw new RuntimeException(e);
    //        }
    //        searchConditionDTO.setColumns(searchAttributeDTOS);
    //        Map<String, SearchAttributeVO> attributeMap = searchAttribute.stream()
    //                .filter(Objects::nonNull)
    //                .filter(attr -> attr.getPropertyName() != null)
    //                .collect(Collectors.toMap(
    //                        attr -> attr.getPropertyName().toLowerCase(),
    //                        Function.identity(),
    //                        (existing, replacement) -> existing
    //                ));
    //        List<SearchAttributeGroupDTO> conditionGroups = new ArrayList<>();//
    //        List<SearchAttributeDTO> conditions = new ArrayList<>();//
    //        for (Object obj : ibaList) {
    //            Map<String, Object> map = (Map<String, Object>) obj;
    //            String value = map.get("CompleteDescription").toString();
    //            if (StringUtils.isNotBlank(value)) {
    //                SearchAttributeVO searchAttributeVO = attributeMap.get("completedescription");
    //                searchAttributeVO.setPropertyValue(value);
    //                searchAttributeVO.setSymbol("=");
    //                SearchAttributeDTO searchAttributeDTO = new SearchAttributeDTO();
    //                try {
    //                    BeanUtils.copyProperties(searchAttributeDTO, searchAttributeVO);
    //                } catch (Exception e) {
    //                    throw new RuntimeException(e);
    //                }
    //                conditions.add(searchAttributeDTO);
    //            }
    //        }
    //        SearchAttributeGroupDTO searchAttributeGroupDTO = new SearchAttributeGroupDTO();
    //        searchAttributeGroupDTO.setConditionJoint("and");
    //        searchAttributeGroupDTO.setConditions(conditions);
    //        conditionGroups.add(searchAttributeGroupDTO);
    //        searchConditionDTO.setConditionGroups(conditionGroups);
    //        searchConditionDTO.setPageNum(1);
    //        searchConditionDTO.setPageSize(PageSizeUtil.getNormalSize(2));
    //        searchConditionDTO.setNeedIBA(false);
    //        searchConditionDTO.setNeedThumbnailFile(false);
    //        searchConditionDTO.setNeedCount(true);
    //        searchConditionDTO.setNoExtProperty(false);
    //        searchConditionDTO.setShowAllViewVersion(false);
    //        searchConditionDTO.setLimitContext(false);
    //        searchConditionDTO.setNeedEmptyCondition(false);
    //        searchConditionDTO.setNeedSort(false);
    //        searchConditionDTO.setNeedLatest(false);
    //        searchConditionDTO.setUsedReport(false);
    //        searchConditionDTO.setExportReport(false);
    //        PageInfo<ResultEntityVO> resultEntityVOPageInfo = typlmCommonSearchService.queryByConditionForPage(searchConditionDTO);
    //        log.info(">>>>>>>>>>{}",resultEntityVOPageInfo);
    //    }

    @Around(value = "execution(* com.hustcad.plm.pdm.partbom.controller.TyplmPartController.insertPart(..))")
    public Object createPart(ProceedingJoinPoint point) {
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new RuntimeException("属性异常");
        }
        HttpServletRequest request = attributes.getRequest();

        List<MultipartFile> fileList = (List<MultipartFile>) point.getArgs()[0];

        UploadFileDTO uploadFileDto = new UploadFileDTO();
        if (CollUtil.isNotEmpty(fileList)) {
            uploadFileDto.setFiles(fileList);
        }

        InsertPartDTO insertPartDto = (InsertPartDTO) JSON.parseObject(request.getParameter("insertPartDto"),
                                                                       InsertPartDTO.class);
        InsertPartDTO insertPartDto2 = null;
        String typeName = (String) JSONObject.parseObject(request.getParameter("insertPartDto")).get("typeName");
        if (Objects.nonNull(insertPartDto)) {
            ArgumentUtils.checkArgumentNull(insertPartDto.getPartView(),
                                            PartBomErrorCodeEnum.EXCEPTION_PARAM_VIEW_ID_IS_EMPTY.getLocaleMessage());
        }

        Map<String, String> descriptionMap = (Map) JSON.parseObject(request.getParameter("descriptionMap"),
                                                                    LinkedMap.class);
        boolean isCreateHyperlinks = false;

        ObjectStorageDO objectStorageDO = objectStorageService.selectOneByTypeDefName(typeName);

        if (StrUtil.isBlank(insertPartDto.getContainerName())) {
            if (Objects.nonNull(objectStorageDO)) {
                insertPartDto.setContainerName(objectStorageDO.getContextName());
                insertPartDto.setFolderName(objectStorageDO.getFolderPath()
                                                    .substring(objectStorageDO.getFolderPath().lastIndexOf("/") + 1));
                insertPartDto.setFolderPath(objectStorageDO.getFolderPath());
            }
        }
        if (ObjectUtil.isEmpty(objectStorageDO) && StrUtil.isBlank(insertPartDto.getContainerType())) {
            return ResponseResult.fail("400", "类型：" + insertPartDto.getTypeDefName() + "未维护对象存储映射");
        }
        if (StrUtil.isBlank(insertPartDto.getContainerType())) {
            insertPartDto.setContainerType("ty.inteplm.product.CTyPDMLinkProduct");
        }
        if ("ty.inteplm.part.CTyPart|PatternCode".equals(insertPartDto.getTypeOType())) {
            LinkedHashMap<String, List<String>> ibaAttribute = insertPartDto.getIbaAttribute();
            List<String> isGenerateMaterialCode = ibaAttribute.get("IsGenerateMaterialCode");
            if (CollUtil.isNotEmpty(isGenerateMaterialCode)) {
                if ("0".equals(isGenerateMaterialCode.get(0))) {
                    checkPartIbaByClass(insertPartDto.getClassId().toString());
                }
            }
        }

        if (StrUtil.isNotBlank(insertPartDto.getContainerType()) && insertPartDto.getContainerType().equals(
                "ty.inteplm.product.CTyPDMLinkProduct")) {

            if (ObjectUtil.isNotEmpty(objectStorageDO)) {
                PDFProjectVO v = storagePlanningMapper.selectPdmIds(objectStorageDO.getContextName());

                String folderId = null;
                if (objectStorageDO.getTypedefName().equals("EBOM号")) {
                    JSONArray jsonArray1 = JSONObject.parseObject(request.getParameter("ibaAttribute"))
                            .getJSONArray(
                                    "ProductLineName");
                    if (CollUtil.isNotEmpty(jsonArray1)) {
                        String ProductLine = jsonArray1.getString(0);
                        if (StrUtil.isNotBlank(ProductLine)) {
                            objectStorageDO.setFolderPath(objectStorageDO.getFolderPath() + "/" + ProductLine);
                        } else {
                            return ResponseResult.fail("400", "产品线名称未维护！");
                        }
                    }

                    String productLineName = "";
                    String productType = ""; // 在外部声明变量
                    JSONArray jsonArray = JSONObject.parseObject(request.getParameter("ibaAttribute"))
                            .getJSONArray("productType");

                    JSONArray devCodeJsonArray = JSONObject.parseObject(request.getParameter("ibaAttribute"))
                            .getJSONArray("devCode");

                    if (CollUtil.isNotEmpty(devCodeJsonArray)) {
                        String devCode = devCodeJsonArray.getString(0);
                        if (StrUtil.isNotBlank(devCode)) {
                            productLineName = devCode;
                        }
                    }

                    if (CollUtil.isNotEmpty(jsonArray)) {
                        productType = jsonArray.getString(0);  // 直接赋值给已声明的变量
                        if (StrUtil.isNotBlank(productType)) {
                            if(StrUtil.isNotBlank(productLineName)) {
                                productLineName = productLineName + "-" + productType;
                            } else {
                                productLineName = productType;
                            }
                        }
                    }
                    if(StringUtils.isNotBlank(productLineName)){
                        objectStorageDO.setFolderPath(objectStorageDO.getFolderPath() + "/" + productLineName);
                    }

                }
                String[] split = objectStorageDO.getFolderPath().split("/");
                for (int i = 0; i < split.length; i++) {
                    String id = null;
                    if (StrUtil.isBlank(split[i])) {
                        continue;
                    }
                    if (i == 1) {
                        id = storagePlanningMapper.selectOidByNameAndCid(v.getOId(),
                                                                         split[i], "0");
                        if (StrUtil.isNotBlank(id)) {
                            folderId = id;
                        }
                    } else {
                        id = storagePlanningMapper.selectOidByNameAndCid(v.getOId(), split[i], folderId);
                        if (StrUtil.isNotBlank(id)) {
                            folderId = storagePlanningMapper.selectOidByNameAndCid(v.getOId(),
                                                                                   split[i], folderId);
                        }

                    }
                    if (StrUtil.isBlank(id)) {
                        //创建文件夹
                        SubfolderVO subfolder = new SubfolderVO();
                        subfolder.setName(split[i]);
                        subfolder.setDescription("--系统自动创建--文件夹--");
                        subfolder.setParentOid(i == 1 ? v.getDefaultcabinetoid() : folderId);
                        subfolder.setParentOtype(
                                i == 1 ? "ty.inteplm.folder.CTyCabinet" : "ty.inteplm.folder.CTySubFolder");
                        SubfolderWebVO subfolderWebVO = typlmSubFolderLinkService.createSubfolder(subfolder);
                        folderId = subfolderWebVO.getOid();
                    }
                }

                insertPartDto.setFolderId(folderId);
                insertPartDto.setContainerID(v.getOId());
                insertPartDto.setContainerType("ty.inteplm.product.CTyPDMLinkProduct");
                insertPartDto.setProductID(v.getOId());
            }
        } else if (StrUtil.isNotBlank(insertPartDto.getContainerType()) && insertPartDto.getContainerType().equals(
                "ty.inteplm.project.CTyProject")) {
            String xxx = storagePlanningMapper.queryExtendedAttributes(insertPartDto.getContainerID(), "密级");
            if (StrUtil.isNotBlank(xxx) && xxx.equals("非密")) {

                if (Objects.nonNull(objectStorageDO)) {
                    PDFProjectVO v = storagePlanningMapper.selectPdmIds(objectStorageDO.getContextName());
                    if (ObjectUtil.isNotEmpty(v)) {
                        isCreateHyperlinks = true;
                        insertPartDto2 = new InsertPartDTO();
                        BeanUtil.copyProperties(insertPartDto, insertPartDto2);

                        insertPartDto.setContainerType("ty.inteplm.product.CTyPDMLinkProduct");
                        insertPartDto.setContainerID(v.getOId());
                        insertPartDto.setProductID(v.getOId());

                        String folderId = null;
                        String cid = v.getDefaultcabinetoid();
                        if (objectStorageDO.getTypedefName().equals("EBOM号")) {
                            JSONArray jsonArray = JSONObject.parseObject(request.getParameter("ibaAttribute"))
                                    .getJSONArray(
                                            "productType");
                            if (CollUtil.isNotEmpty(jsonArray)) {
                                String productType = jsonArray.getString(0);
                                if (StrUtil.isNotBlank(productType)) {
                                    objectStorageDO.setFolderPath(objectStorageDO.getFolderPath() + "/" + productType);
                                }
                            }
                        }
                        String[] split = objectStorageDO.getFolderPath().split("/");
                        for (int i = 0; i < split.length; i++) {
                            String id = null;
                            if (StrUtil.isBlank(split[i])) {
                                continue;
                            }
                            if (i == 1) {
                                id = storagePlanningMapper.selectOidByNameAndCid(v.getOId(),
                                                                                 split[i], "0");
                                if (StrUtil.isNotBlank(id)) {
                                    folderId = id;
                                }
                            } else {
                                id = storagePlanningMapper.selectOidByNameAndCid(v.getOId(), split[i], folderId);
                                if (StrUtil.isNotBlank(id)) {
                                    folderId = storagePlanningMapper.selectOidByNameAndCid(v.getOId(),
                                                                                           split[i], folderId);
                                }

                            }
                            if (StrUtil.isBlank(id)) {
                                //创建文件夹
                                SubfolderVO subfolder = new SubfolderVO();
                                subfolder.setName(split[i]);
                                subfolder.setDescription("--系统自动创建--文件夹--");
                                subfolder.setParentOid(i == 1 ? v.getDefaultcabinetoid() : folderId);
                                subfolder.setParentOtype(
                                        i == 1 ? "ty.inteplm.folder.CTyCabinet" : "ty.inteplm.folder.CTySubFolder");
                                SubfolderWebVO subfolderWebVO = typlmSubFolderLinkService.createSubfolder(subfolder);
                                folderId = subfolderWebVO.getOid();
                            }
                        }
                        insertPartDto.setFolderId(folderId);
                    }
                }

            }
        }



        try {
            PdmPartInfoVO partInfoVO = this.typlmPdmPartService.insertPart(uploadFileDto, descriptionMap,
                                                                           insertPartDto);

            if (isCreateHyperlinks) {
                //创建超链接
                HyperlinkDTO hyperlinkDTO = docFolderOperationService.assignmentToHyperlinkDTO(insertPartDto2,
                                                                                               partInfoVO);
                List<HyperlinkDTO> l = new ArrayList<>();
                l.add(hyperlinkDTO);
                typlmHyperlinkService.batchCreateHyperlink(l);
            }

            return ResponseResult.success(partInfoVO);
        } catch (Exception var8) {
            if (insertPartDto != null) {
                AuditLogDO auditLogDO = new AuditLogDO();
                auditLogDO.setObjoid(BigInteger.ZERO);
                auditLogDO.setObjotype("ty.inteplm.part.CTyPart");
                auditLogDO.setContaineroidStr(insertPartDto.getContainerID());
                auditLogDO.setContainerotype(insertPartDto.getContainerType());
                auditLogDO.setTargetname(insertPartDto.getName());
                auditLogDO.setTargetnumber(insertPartDto.getPartNumber());
                auditLogDO.setTargetsecuritylabels(insertPartDto.getSecuritylabels());
                auditLogDO.setFolderpath(insertPartDto.getFolderPath());
                TyplmAuditLogUtil.errorInfo(LogEventEnum.CRATE_OBJECT, auditLogDO, var8);
            }

            throw var8;
        }
    }

    @Resource
    private RTClassificationMapper rtClassificationMapper;

    @Resource
    private TyplmTypeService typlmTypeService;

    @Resource
    private TyplmDefaultValueService typlmDefaultValueService;


    private Map<String,TyAttributeDefMapVO> collectPartIba(String classId){
        BigInteger parentClassByChildClassId = rtClassificationMapper.getParentClassByChildClassId(classId);
        List<TyAttributeDefMapVO> tyAttributeDefMapVOS = typlmTypeService.queryInheritAttrDef(parentClassByChildClassId,
                                                                                              TableTypeConstrant.TY_CLASSIFICATION_OTYPE);
        // 使用 Stream 将 TyAttributeDefMapVO 列表转换为以 name 为 key 的 Map
        return tyAttributeDefMapVOS.stream()
                .collect(Collectors.toMap(TyAttributeDefMapVO::getName, Function.identity()));
    }

    private void checkPartIbaByClass(String classId){
        List<String> errorList = new ArrayList<>();
        BigInteger parentClassByChildClassId = rtClassificationMapper.getParentClassByChildClassId(classId);
        List<TyAttributeDefMapVO> attrDefMapList = typlmTypeService.queryInheritAttrDef(parentClassByChildClassId, TableTypeConstrant.TY_CLASSIFICATION_OTYPE);
        for(TyAttributeDefMapVO tyAttributeDefMapVO : attrDefMapList){
            Map<String, TyplmDefaultValueParamDTO> map = new HashMap<>();
            TyplmDefaultValueParamDTO typlmDefaultValueParamDTO = new TyplmDefaultValueParamDTO();
            typlmDefaultValueParamDTO.setEntity(new IdentifierEntity(tyAttributeDefMapVO.getOid(),tyAttributeDefMapVO.getOtype()));
            map.put(TableTypeConstrant.TY_CLASSIFICATION_OTYPE + ":" + parentClassByChildClassId, typlmDefaultValueParamDTO);
            Map<String, List<TyplmAttrDefaultValueDTO>> entityDefaultValueList = typlmDefaultValueService.getEntityDefaultValueList(map);
            for (List<TyplmAttrDefaultValueDTO> value : entityDefaultValueList.values()) {
                TyplmAttrDefaultValueDTO defaultValueDTO = value.get(0);
                String isInherit = defaultValueDTO.getIsInherit();
                if("0".equals(isInherit)){
                    String defaultValue = defaultValueDTO.getDefaultValue();
                    if(StringUtils.isBlank(defaultValue)){
                        errorList.add(tyAttributeDefMapVO.getDisplayName());
                    }
                }
            }
        }
        if (CollUtil.isNotEmpty(errorList)) {
            throw RTErrorCodeEnum.DEV_CODE_EXIST.getException(
                    "属性:" + String.join(",", errorList) + "不存在，不可创建！");
        }
    }

    //根据选择，判断是否需要生成物料编码
    //    @SneakyThrows
    //    @Around(value = "execution(* com.hustcad.plm.pdm.middle.partbom.service.TyplmPdmPartService.insertPart(..))")
    //    public Object createPartDrawingCode(ProceedingJoinPoint point) {
    //        Object[] args = point.getArgs();
    //        if (args.length < 3) {
    //            return point.proceed();
    //        }
    //        UploadFileDTO uploadFileDto = (UploadFileDTO) args[0];
    //        Map<String, String> descriptionMap = (Map<String, String>) args[1];
    //        InsertPartDTO insertPartDto = (InsertPartDTO) args[2];
    //        // 添加类型校验
    //        if (!codeDrawingMapper.selectTypeFromDefaultIteratedOid(insertPartDto.getTypeOid()).equals("图样代号")) {
    //            return point.proceed();
    //        }
    //        PdmPartInfoVO partInfoVO=(PdmPartInfoVO) point.proceed();
    //
    //
    //        PdmPartsInfoVO pdmPartsInfoVO = new PdmPartsInfoVO();
    //        BeanUtil.copyProperties(partInfoVO, pdmPartsInfoVO);
    //        // 如果生成物料编码为true，则生成物料编码
    //        List<String> generateMaterialCode = insertPartDto.getIbaAttribute().get("generateMaterialCode");
    //        if (CollUtil.isNotEmpty(generateMaterialCode) && generateMaterialCode.get(0).equals("true")) {
    //            pdmPartsInfoVO.setMaterialCode(processNumberMapper.generateMaterialCode());
    //            return pdmPartsInfoVO;
    //        }
    //        return point.proceed();
    //    }

    // ... 其他代码保持不变 ...

//    @SneakyThrows
//    @Around(value = "execution(* com.hustcad.plm.pdm.form.service.TyplmDynamicFormService.getPdmFormWithData(..))")
//    public Object materialCodeReturn(ProceedingJoinPoint point) {
//        String type = (String) point.getArgs()[0];
//        PdmForm result = (PdmForm) point.proceed();
//        List<PdmFormColumn> formData = result.getFormData();
//        if (type.equals("MaterialCode")) {
//            for (PdmFormColumn column : formData) {
//
//
//            }
//        }
//
//        return result;
//    }

    @SneakyThrows
    @Around(value = "execution(* com.hustcad.plm.pdm.comment.service.TyplmCommentService.queryCommentCount(..))")
    public Object deleteComment(ProceedingJoinPoint point) {
        QueryCommentCountDTO queryCommentCountDTO = (QueryCommentCountDTO) point.getArgs()[0];
        Map<String, List<BigInteger>> map = new HashMap<>();
        // 3. 也可以直接在put时创建List（简化写法）
        IdentifierEntity identifierEntity = new IdentifierEntity(new BigInteger("1000000000000000"),
                                                                 "ty.inteplm.part.CTyPart");
        queryCommentCountDTO.setEntityList(Collections.singletonList(identifierEntity));

        // 修复类型转换问题
        Object result = point.proceed();
        if (result instanceof PdmForm) {
            return result;
        } else {

            // 1. 创建CommentCountVO对象
            CommentCountVO commentCountVO = new CommentCountVO();

            // 2. 为各属性赋值
            // 注意：BigInteger需通过构造方法初始化（如传入数字字符串）
            commentCountVO.setObjBaseOid(new BigInteger("100000000000000000001")); // 大整数ID
            commentCountVO.setObjBaseOtype("TASK"); // 对象类型（例如：任务）

            // 整数类型属性直接赋值
            commentCountVO.setAllCount(50); // 总评论数
            commentCountVO.setUnresolvedCount(15); // 未解决评论数
            commentCountVO.setResolvedCount(35); // 已解决评论数
            commentCountVO.setUnresolvedDefectCount(5); // 未解决缺陷数
            commentCountVO.setResolvedDefectCount(20); // 已解决缺陷数


            return Collections.singletonList(commentCountVO); // 或者根据业务需求返回适当的默认值
        }

    }

    @Resource
    private TyplmClassificationService typlmClassificationService;

    /**
     * 编辑页面增加逻辑处理
     *
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.hustcad.plm.pdm.form.service.impl.TyplmDynamicFormServiceImpl.getPdmFormWithData(java.lang.String, java.lang.String, " +
            "java.lang.String, java.lang.String, java.lang.Class, java.lang.String, java.lang.String))")
    public Object getPdmFormWithData(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        String classificationOid = (String)proceedingJoinPoint.getArgs()[6];
        Object proceed = proceedingJoinPoint.proceed();
        if (proceed instanceof PdmForm) {
            PdmForm pdfForm = (PdmForm) proceed;
            String type = pdfForm.getType();
            String formLabel = pdfForm.getFormLabel();
            List<PdmFormColumn> formData = pdfForm.getFormData();
            if("editScreen".equals(formLabel)){
                // 标准件 Standard
                if ("Standard".equals(type)) {
                    for (PdmFormColumn pdmFormColumn : formData) {
                        String prop = pdmFormColumn.getProp();
                        if ("performance".equals(prop) || "screwPitch".equals(prop) ||
                                "specialRequirement".equals(prop) || "specification".equals(prop) ||
                                "surfaceTreatment".equals(prop) || "hazardousSubstance".equals(prop)) {
                            pdmFormColumn.setReadOnly(true);
                        }
                    }
                } else if ("PatternCode".equals(type)) { // 图样代号  PatternCode
                    TyplmClassificationEntityDTO currentClassInfo = typlmClassificationService.queryClassificationDTOByOID(
                            new BigInteger(classificationOid));
                    String parentOid = currentClassInfo.getParentOid();
                    TyplmClassificationEntityDTO parentClassInfo = typlmClassificationService.queryClassificationDTOByOID(
                            new BigInteger(parentOid));
                    Map<String, TyAttributeDefMapVO> tyAttributeDefMapVOS = buildExclusiveAttrMap(parentClassInfo);
                    for (PdmFormColumn pdmFormColumn : formData) {
                        String prop = pdmFormColumn.getProp();
                        if(tyAttributeDefMapVOS.containsKey(prop)){
                            pdmFormColumn.setReadOnly(true);
                        }
                    }
                }else if("MaterialCode".equals(type)) {// 物料码  MaterialCode
                    TyplmClassificationEntityDTO currentClassInfo = typlmClassificationService.queryClassificationDTOByOID(
                            new BigInteger(classificationOid));
                    Map<String, TyAttributeDefMapVO> stringTyAttributeDefMapVOMap = buildExclusiveAttrMap(currentClassInfo);
                    setReadOnlyAttributes(formData, stringTyAttributeDefMapVOMap);
                }
            }else if("add".equals(formLabel)){
                if("ProductSpectrum".equals(type)) {// 物料码  MaterialCode
                    if(StringUtils.isNotBlank(classificationOid)) {
                        TyplmClassificationEntityDTO currentClassInfo = typlmClassificationService.queryClassificationDTOByOID(
                                new BigInteger(classificationOid));
                        for (PdmFormColumn pdmFormColumn : formData) {
                            String prop = pdmFormColumn.getProp();
                            if("ProductLineName".equals(prop)) {
                                pdmFormColumn.setValue(currentClassInfo.getDisplayName());
                            }
                        }
                    }
                }
            }
        }
        return proceed;
    }

    private void setReadOnlyAttributes(List<PdmFormColumn> formData, Map<String, TyAttributeDefMapVO> attrMap) {
        for (PdmFormColumn formColumn : formData) {
            String ibaEnName = formColumn.getIbaEnName();
            if (attrMap.containsKey(ibaEnName)) {
                formColumn.setReadOnly(true);
            }
        }
    }

    private @NotNull Map<String, TyAttributeDefMapVO> buildExclusiveAttrMap(
            TyplmClassificationEntityDTO currentClassInfo) {
        List<TyAttributeDefMapVO> currentClassAttrDefMapList = this.typlmTypeService.queryInheritAttrDef(new BigInteger(
                currentClassInfo.getId()), currentClassInfo.getOtype());
        currentClassAttrDefMapList.forEach((attr) -> {
            attr.setIbaDefType(TyplmEntityBaseUtil.getAttributeTypeDisplay(attr.getIbaDefType()));
        });

        // 图样代号专有属性
        return currentClassAttrDefMapList.stream()
                .filter(attr -> "0".equals(attr.getIsInherit()))
                .collect(Collectors.toMap(
                        TyAttributeDefMapVO::getName,
                        Function.identity(),
                        (v1, v2) -> v1
                ));
    }


}